﻿#Include ..\baseHandle.ahk

#Include ..\..\_lib\WinHttpRequest.ahk
#Include ..\..\_lib\Unicodes.ahk

class Http extends BaseHandle {

  static Handle(parsed) {
    method := parsed.kvparams['X'] || 'GET'
    data := parsed.kvparams['d'] || unset ; string
    query := parsed.kvparams['q'] || '' ; string
    header := parsed.kvparams['H'] || []
    headers := {}, url := parsed.target

    for v in header
      _ := InStr(v, ':'), headers[Trim(v.substring(1, _))] := Trim(v.substring(_ + 1))
    url .= query && ((InStr(url, '?') ? '&' : '?') query)
    res := WinHttpRequest().request(url, method, data?, headers)
    return this.Succ(DecodeUniCodeString(res))
  }

  static Spec() {
    return {
      cmd: 'http',
      desc: '发送 HTTP 请求',
      format: 'http [-X=?] [-d=?] [-q=?] [-H=?] <url>',
      params: [],
      kvparams: [{
        name: 'X',
        desc: '请求方法'
      }, {
        name: 'd',
        desc: '请求体'
      }, {
        name: 'q',
        desc: '查询参数'
      }, {
        name: 'H',
        desc: '请求头'
      }],
      args: {
        desc: '',
        isOptional: false,
        cacheable: false,
        generator: {
          script: '',
          postProcess: Noop
        }
      },
      extra: {
        isEnable: false,
        isMulti: false,
      }
    }
  }
}
